# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import re
from datetime import datetime, timedelta
from PIL import Image, ImageFilter, ImageEnhance
import time
import StringIO
import os
import sys
# import json


def code(req):
    while True:
        pic = urllib2.urlopen(req).read()
        # pic_name="old.jpg"
        # f = open(pic_name, 'wb')
        # f.write(pic)
        # f.close
        # time.sleep(5)
        # box=(0,0,60,20)
        im = StringIO.StringIO(pic)
        # im.save(pic_name)
        im = Image.open(im)
        # im=im.crop(box)
        # im=im.filter(ImageFilter.MedianFilter())
        # enhancer = ImageEnhance.Contrast(im)
        # im = enhancer.enhance(1)
        # im = im.convert('L')
        # im.show()
        im.save("code.jpg")

        os.popen('tesseract.exe code.jpg code')
        t = open('code.txt').read()
        print "txt:", t
        pattern = r'[0-9]'
        t = re.findall(pattern, t)
        if(len(t) == 4):
            return "".join(t)
        # print "check:","".join(t)


def login(str):
    pattern = r'<font color="#FF3300" >GUEST</font>'
    # print re.search(pattern,str).group(0)
    return re.search(pattern, str)
# ##########################################
# 主程序开始
# ##########################################
# 定义查询的日期
# 定义更新的报关单数量
# 使用cookie
cookie_support = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
# 登录信息
pic_req = urllib2.Request(url="http://www.npedi.com/edi/ediweb/image.jsp")
# print code(pic_req)
login_post_data = urllib.urlencode({
    'usercode': 'GUEST',
    'password': 'guest',
    'randcode': code(pic_req)
})
# 登录的地址
login_req = urllib2.Request(
    url='http://www.npedi.com/edi/webLoginAction.do',
    data=login_post_data
)
bLogin = login(urllib2.urlopen(login_req).read())


print bLogin
for x in (300, 600, 900, 1200, 1500, 1800, 2100, 2400, 2700, 3000):
    print time.time()
    login_req = urllib2.Request(
        url='http://www.npedi.com/edi/webLoginAction.do'
    )
    bLogin = login(urllib2.urlopen(login_req).read())
    print bLogin
    print '%s sec wait' % x
    time.sleep(x)
